<?php
namespace Swiftx\Component\Orm\Statement;
use Swiftx\Interfaces\Orm\Entity;
use Swiftx\Interfaces\Orm\Pager as InterfacePager;

class Pager implements InterfacePager {

    /**
     * 当前页码
     * @var int
     */
    protected $current;

    /**
     * 总记录数
     * @var int
     */
    protected $total;

    /**
     * 每页显示记录数
     * @var int
     */
    protected $number;

    /**
     * 分页数据
     * @var Entity[]
     */
    protected $data;

    /**
     * 加载器
     * @var callable
     */
    protected $loader;

    /**
     * 统计器
     * @var callable
     */
    protected $counter;

    /**
     * 同步时间
     * @var int
     */
    protected $syncTime = 0;

    /**
     * 设置当前页面
     * @param int $value
     */
    public function setCurrent(int $value){
        $this->current = $value;
    }

    /**
     * 每页显示记录数
     * @param int $value
     */
    public function setNumber(int $value){
        $this->number = $value;
    }

    /**
     * 每页显示记录数
     * @return int
     */
    public function getNumber():int{
        return $this->number;
    }

    /**
     * 设置计数器
     * @param callable $func
     */
    public function setCounter(callable $func){
        $this->counter = $func;
    }

    /**
     * 设置加载器
     * @param callable $func
     */
    public function setLoader(callable $func){
        $this->loader = $func;
    }

    /**
     * 是否进行了数据同步
     * @return bool
     */
    public function isSync():bool {
        return $this->syncTime?true:false;
    }

    /**
     * 执行数据加载同步
     */
    public function runSync(){
        if(!is_callable($this->counter))
            throw new \ErrorException('计数器设置不正确');
        if(!is_callable($this->loader))
            throw new \ErrorException('加载器设置不正确');
        $this->total = call_user_func($this->counter);
        $limit = ($this->current-1)*$this->number;
        $this->data = call_user_func($this->loader, $limit, $this->number);
        $this->syncTime = time();
    }

    /**
     * 获取总记录数
     * @return int
     */
    public function getTotal():int{
        return $this->total;
    }

    /**
     * 获取总页数
     * @return int
     */
    public function getCount():int{
        return ceil($this->getTotal()/$this->getNumber());
    }

    /**
     * 读取页面数据
     * @return Entity[]
     */
    public function getData():array {
        return $this->data;
    }

}